<template>
  group chat:
  <div>
    <button @click="connect">连接</button> &nbsp;
    <button @click="disconnect">断开连接</button>
  </div>
  <div>
    名字：<input type="text" v-model="name" />

    消息： <input type="text" v-model="content" />
    <button @click="sendMessage">发送消息</button>

    <div class="bubble"></div>
    <div>
      <div v-for="(msg, key) in messages" :key="key">
        {{ msg.name }}:{{ msg.content }}
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, toRefs } from 'vue'
const data = reactive({
  name: '',
  content: '',
  messages: [],
})
const { name, content, messages } = toRefs(data)

let stomp = null

function sendMessage() {
  const msg = {
    name: data.name,
    content: data.content,
  }
  stomp.send('/app/hello', {}, JSON.stringify(msg))
  data.content = ''
}

// 'Connect' button click handler
function connect() {
  stomp = Stomp.over(new SockJS('http://localhost:8080/websocket'))

  stomp.connect({}, (frame) => {
    const subscription = stomp.subscribe('/topic/greetings', (res) => {
      console.log('message:', res.body)

      data.messages.push(JSON.parse(res.body))
    })
  })
}

// 'Disconnect' button click handler
function disconnect() {
  if (stomp !== null) {
    stomp.disconnect(function () {
      console.log('Client disconnected')
    })
    stomp = null
  }
}
</script>

<style lang="scss" scoped></style>
